package zut.wework.utils;


import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import zut.wework.api.WorkWXAPI;
import zut.wework.entity.WxUser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 韩云飞
 * @Date 2018/1/17 9:28
 * @Desc 微信API帮助类
 */
@Component
public class WXAPIUtil {

    private final static Logger logger = LoggerFactory.getLogger(WXAPIUtil.class);

    public static String accessTokenAuth = "access_token:auth";

    public static String accessTokenContacts = "access_token:contacts";

    public static String accessTokenHelper = "access_token:helper";

    public static String jsAPITicket = "access_token:jsapi";

//    /**
//     * 获取access token
//     * @param key 根据此key获取
//     * @return
//     */
//    public static Map<String, Object> getAccessToken(String key){
//        String secret = "";
//        if(key == accessTokenAuth){
//            secret = WorkWXAPI.AUTH_APP_SECRET;
//        }else if(key == accessTokenContacts){
//            secret = WorkWXAPI.CONTACTS_SECRET;
//        }else if(key == accessTokenHelper){
//            secret = WorkWXAPI.HELPER_SECRET;
//        }
//        String json = HttpClientUtil.get(String.format(WorkWXAPI.GET_ACCESS_TOKEN_URL, WorkWXAPI.CORPID, secret));
//        Map<String, Object> data = JsonUtil.WXJsonToMap(json);
//        if (Integer.parseInt(data.get("errcode").toString()) == 0) {
//            return  data;
//        } else {
//            logger.info("{} get access error,msg:{}", key, data.toString());
//        }
//        return null;
//    }

    /**
     * 根据code获取用户信息
     * @param code
     * @return
     */
    public static Map<String, Object> getOpenId(String code){

       return HttpClientUtil.wxRequest(accessTokenAuth, String.format(WorkWXAPI.GET_USER_OPENID_URL, accessTokenAuth, code)
                , null, HttpClientUtil.METHOD_GET);
    }

    /**
     * 根据UserId获取用户信息
     * @param userId
     * @return
     */
    public static Map<String, Object> getContact(String userId){

        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.CONTACTS_GET, accessTokenContacts, userId)
                , null, HttpClientUtil.METHOD_GET);
    }

    /**
     * 更新用户信息
     * @param json
     * @return
     */
    public static Map<String, Object> updateContact(String json){

        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.CONTACTS_UPDATE, accessTokenContacts)
                , json, HttpClientUtil.METHOD_POST);
    }

    /**
     * 创建用户信息
     * @param json
     * @return
     */
    public static Map<String, Object> createContact(String json){

        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.CONTACTS_CREATE, accessTokenContacts)
                , json, HttpClientUtil.METHOD_POST);
    }

    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    public static Map<String, Object> deleteContact(String userId){

        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.CONTACTS_DELETE, accessTokenContacts, userId)
                , null, HttpClientUtil.METHOD_GET);
    }

    /**
     * 发送消息
     * @param msg
     * @return
     */
    public static Map<String, Object> sendMsg(Map<String, Object> msg){

        return HttpClientUtil.wxRequest(accessTokenHelper, String.format(WorkWXAPI.SEND_MESSAGE_URL, accessTokenHelper)
                , JsonUtil.toJson(msg), HttpClientUtil.METHOD_POST);
    }

    /**
     * 执行创建部门操作
     * @param name 部门名称
     * @param parentid 父部门id
     * @param  order 排序(不指定时传入0)
     * @return
     */
    public static Map<String, Object> createDepartment(String name, Integer parentid, Integer order){
        Map<String, Object> createMap = new HashMap<>();
        createMap.put("name", name);
        createMap.put("parentid", parentid);
        if(order > 0){
            createMap.put("order", order);
        }
        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.DEPARTMENT_CREATE, accessTokenContacts),
                JsonUtil.toJson(createMap), HttpClientUtil.METHOD_POST);
    }

    /**
     * 获取企业微信的教职工所在部门列表
     * @param departmentId 企业微信部门ID
     * @return
     */
    public static Map<Integer, Map<String, Object>> getDepartment(Integer departmentId){
        Map<Integer, Map<String, Object>> departmentMap = new HashMap<>();
        Map<String, Object> jsonMap = HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.DEPARTMENT_LIST,
                accessTokenContacts, String.valueOf(departmentId)), null, HttpClientUtil.METHOD_GET);
        if(Integer.parseInt(jsonMap.get("errcode").toString()) == 0){
            List<Map<String, Object>> list = (List<Map<String, Object>>) jsonMap.get("department");

            for(Map<String, Object> map : list){
                departmentMap.put(Integer.parseInt(map.get("id").toString()), map);
            }
        }
        return departmentMap;
    }

    /**
     * 执行更新部门操作
     * @param json 部门信息
     * @return
     */
    public static Map<String, Object> updateDepartment(String json){
        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.DEPARTMENT_UPDATE, accessTokenContacts),
                json, HttpClientUtil.METHOD_POST);
    }


    /**
     *获取企业微信教职工信息-详细
     * @param departmentId
     * @return
     */
    public static List<Map<String, Object>> getContactsDetail(Integer departmentId){
        Map<String, Object> jsonMap = HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.CONTACTS_LIST,
                accessTokenContacts, String.valueOf(departmentId), "1"), null, HttpClientUtil.METHOD_GET);
        List<Map<String, Object>> list = new ArrayList<>();
        if(Integer.parseInt(jsonMap.get("errcode").toString()) == 0) {
            list = (List<Map<String, Object>>) jsonMap.get("userlist");
        }
        return list;
    }

    /**
     *获取企业微信教职工信息
     * @param departmentId
     * @return
     */
    public static List<Map<String, Object>> getContacts(Integer departmentId){
        Map<String, Object> jsonMap = HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.CONTACTS_SIMPLE_LIST,
                accessTokenContacts, String.valueOf(departmentId), "1"), null, HttpClientUtil.METHOD_GET);
        List<Map<String, Object>> list = new ArrayList<>();
        if(Integer.parseInt(jsonMap.get("errcode").toString()) == 0) {
            list = (List<Map<String, Object>>) jsonMap.get("userlist");
        }
        return list;
    }

    /**
     * 获取微信用户信息
     * @param userId
     * @return
     */
    public static WxUser getUserInfo(String userId){
        try{
            Map<String, Object> map = HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.GET_USER_INFO,
                    accessTokenContacts, userId), null, HttpClientUtil.METHOD_GET);
            if(Integer.parseInt(map.get("errcode").toString()) == 0) {
                map.remove("errcode");
                map.remove("errmsg");
                WxUser wxUser = new WxUser();
                MapToObject.mapToBean(map, wxUser);
                return wxUser;
            }
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage());
        }
        return null;
    }

    /**
     * 创建标签
     * @param tagName 标签名称
     * @return
     */
    public static Map<String, Object> createTag(String tagName){
        Map<String, String> map = new HashMap<>();
        map.put("tagname", tagName);
        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.TAG_CREATE, accessTokenContacts),
                JsonUtil.toJson(map), HttpClientUtil.METHOD_POST);
    }

    /**
     * 增加标签成员
     * @param tagId 标签ID
     * @param userIdList 企业成员ID列表
     * @return
     */
    public static List<Map<String, Object>> addTagUsers(int tagId, List<String> userIdList){
        List<List<String>> userIdLists = Lists.partition(userIdList, 1000); //1000个分割一次

        List<Map<String, Object>> returnData = new ArrayList<>();
        for(List<String> tempUserIdList : userIdLists){
            Map<String, Object> map = new HashMap<>();
            map.put("tagid", tagId);
            map.put("userlist", tempUserIdList);
            Map<String, Object> jsonMap = HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.TAG_ADD_USERS_URL, accessTokenContacts),
                    JsonUtil.toJson(map), HttpClientUtil.METHOD_POST);
            returnData.add(jsonMap);
        }
        return returnData;
    }

//    /**
//     * 删除标签成员
//     * @param tagId 标签ID
//     * @param userIdList 企业成员ID列表
//     * @return
//     */
//    public static Map<String, Object> delTagUsers(int tagId, List<String> userIdList){
//        Map<String, Object> map = new HashMap<>();
//        map.put("tagid", tagId);
//        map.put("userlist", userIdList);
//        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.TAG_DELETE_USERS_URL, accessTokenContacts),
//                JsonUtil.toJson(map), HttpClientUtil.METHOD_POST);
//    }
//
//    public static Map<String, Object> getJsAPI(){
//
//        return HttpClientUtil.wxRequest(accessTokenContacts, String.format(WorkWXAPI.JS_API, accessTokenContacts), null, HttpClientUtil.METHOD_GET);
//    }

}
